import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';
import { ComponentLibraryConfig, ComponentDefinition } from '@/types/component';
import { ComponentDataStore } from '@/config/component-data';

// JSON组件数据加载器
export class ComponentLoader {
    private dataStore = ComponentDataStore.getInstance();
    private configSearchPaths: string[] = [];

    constructor(private context: vscode.ExtensionContext) {
        // 初始化时加载配置
        this.loadConfiguration();
        
        // 监听配置变化
        this.setupConfigurationWatcher();
    }

      /**
     * 加载配置设置
     */
    private loadConfiguration(): void {
        const config = vscode.workspace.getConfiguration('componentCompletion');
        this.configSearchPaths = config.get<string[]>('configSearchPaths') || [];
        console.log(`加载配置搜索路径: ${JSON.stringify(this.configSearchPaths)}`);
    }

      /**
     * 设置配置变化监听
     */
    private setupConfigurationWatcher(): void {
        // 监听VSCode配置变化
        vscode.workspace.onDidChangeConfiguration((event) => {
            if (event.affectsConfiguration('componentCompletion.configSearchPaths')) {
                console.log('检测到配置路径变化，重新加载配置');
                this.loadConfiguration();
            }
        });
    }

    // 从JSON文件加载组件库配置
    async loadLibraryFromJson(libraryName: string): Promise<boolean> {
        try {
            const filePath = await this.findJsonConfigFile(libraryName);
            if (!filePath) {
                console.warn(`未找到 ${libraryName} 的JSON配置文件`);
                return false;
            }

            console.log(`正在加载组件库: ${libraryName}, 文件路径: ${filePath}`);

            const fileContent = await fs.promises.readFile(filePath, 'utf-8');
            const config: ComponentLibraryConfig = JSON.parse(fileContent);

            // 验证配置格式
            if (!this.validateConfig(config)) {
                throw new Error('无效的组件库配置格式');
            }

            // 解析并存储组件数据
            this.parseAndStoreComponents(config);

            console.log(`成功加载 ${libraryName} 组件库，包含 ${Object.keys(config.components).length} 个组件`);
            return true;

        } catch (error: unknown) {
            console.error(`加载组件库 ${libraryName} 失败:`, error);
            vscode.window.showErrorMessage(`加载组件库 ${libraryName} 失败: ${error instanceof Error ? error.message : '未知错误'}`);
            return false;
        }
    }

    // 查找JSON配置文件
    private async findJsonConfigFile(libraryName: string): Promise<string | null> {
        const possibleFileNames = [
            `${libraryName}.json`,
            `${libraryName}-components.json`,
            `components-${libraryName}.json`
        ];

         // 获取所有要搜索的路径
        const searchPaths = await this.getAllSearchPaths();

        // 检查所有可能的路径和文件名组合
       // 检查所有可能的路径和文件名组合
        for (const basePath of searchPaths) {
            // 解析路径中的特殊符号
            const resolvedPath = this.resolvePath(basePath);
            
            if (!resolvedPath) {
                continue;
            }

            // 检查路径是否存在
            if (!fs.existsSync(resolvedPath)) {
                console.log(`配置路径不存在: ${resolvedPath}`, 'warn');
                continue;
            }

            for (const fileName of possibleFileNames) {
                const fullPath = path.join(resolvedPath, fileName);
                
                if (fs.existsSync(fullPath)) {
                    console.log(`找到配置文件: ${fullPath}`);
                    return fullPath;
                }
            }
        }

        return null;
    }

      /**
     * 获取所有搜索路径（包括默认路径和配置路径）
     */
    private async getAllSearchPaths(): Promise<string[]> {
        const allPaths: string[] = [];

        // 1. 默认路径
        const defaultPaths = [
            path.join(this.context.extensionPath, 'component-data'),
            path.join(require('os').homedir(), '.vscode', 'component-completion')
        ];

        // 2. 工作区根目录（如果存在）
        if (vscode.workspace.rootPath) {
            defaultPaths.push(vscode.workspace.rootPath);
            defaultPaths.push(path.join(vscode.workspace.rootPath, '.vscode'));
        }

        // 3. 用户配置的路径
        for (const configPath of this.configSearchPaths) {
            const resolvedPath = this.resolvePath(configPath);
            if (resolvedPath) {
                allPaths.push(resolvedPath);
            }
        }

        // 4. 添加默认路径（去重）
        for (const defaultPath of defaultPaths) {
            if (!allPaths.includes(defaultPath) && fs.existsSync(defaultPath)) {
                allPaths.push(defaultPath);
            }
        }

        return allPaths;
    }

    /**
     * 解析路径中的特殊符号
     */
    private resolvePath(rawPath: string): string | null {
        try {
            let resolvedPath = rawPath;

            // 解析 ~ 为用户主目录
            if (resolvedPath.startsWith('~/') || resolvedPath === '~') {
                resolvedPath = path.join(require('os').homedir(), resolvedPath.substring(1));
            }

            // 解析 ./ 为相对路径（相对于工作区）
            if (resolvedPath.startsWith('./') && vscode.workspace.rootPath) {
                resolvedPath = path.join(vscode.workspace.rootPath, resolvedPath.substring(2));
            }

            // 解析 ../ 为相对路径
            if (resolvedPath.startsWith('../') && vscode.workspace.rootPath) {
                resolvedPath = path.join(vscode.workspace.rootPath, resolvedPath);
            }

            // 解析环境变量
            if (resolvedPath.includes('${')) {
                resolvedPath = this.resolveEnvironmentVariables(resolvedPath);
            }

            return path.resolve(resolvedPath);
        } catch (error: any) {
            console.log(`解析路径失败: ${rawPath}, 错误: ${error.message}`, 'error');
            return null;
        }
    }

     /**
     * 解析环境变量
     */
    private resolveEnvironmentVariables(pathWithEnvVars: string): string {
        return pathWithEnvVars.replace(/\$\{([^}]+)\}/g, (match, envVar) => {
            return process.env[envVar] || match;
        });
    }


    // 验证配置格式
   private validateConfig(config: any): config is ComponentLibraryConfig {
        if (!config || typeof config !== 'object') {
            throw new Error('配置必须是JSON对象');
        }

        if (typeof config.library !== 'string') {
            throw new Error('配置必须包含 library 字符串字段');
        }

        if (!config.components || typeof config.components !== 'object') {
            throw new Error('配置必须包含 components 对象字段');
        }

        return true;
    }

    // 解析并存储组件数据
     private parseAndStoreComponents(config: ComponentLibraryConfig): void {
        for (const [componentName, componentData] of Object.entries(config.components)) {
            try {
                const component: ComponentDefinition = {
                    name: componentData.name || componentName,
                    aliases: componentData.aliases || [],
                    description: componentData.description || '',
                    importPath: componentData.importPath || config.library,
                    props: componentData.props || []
                };

                // 验证组件数据
                this.validateComponent(component, componentName);

                // 存储组件
                this.dataStore.addComponent(component, config.library);

                console.log(`成功解析组件: ${component.name}`);

            } catch (error: any) {
                console.log(`解析组件 ${componentName} 失败: ${error.message}`, 'error');
            }
        }
    }

     /**
     * 验证组件数据
     */
    private validateComponent(component: ComponentDefinition, originalName: string): void {
        if (!component.name || typeof component.name !== 'string') {
            throw new Error(`组件 ${originalName} 的 name 字段必须是非空字符串`);
        }

        if (!component.description || typeof component.description !== 'string') {
            throw new Error(`组件 ${component.name} 的 description 字段必须是非空字符串`);
        }

        if (!Array.isArray(component.props)) {
            throw new Error(`组件 ${component.name} 的 props 字段必须是数组`);
        }

        // 验证属性
        for (const prop of component.props) {
            if (!prop.name || typeof prop.name !== 'string') {
                throw new Error(`组件 ${component.name} 的属性 name 必须是非空字符串`);
            }

            if (!prop.type || typeof prop.type !== 'string') {
                throw new Error(`组件 ${component.name} 的属性 ${prop.name} 的 type 必须是非空字符串`);
            }

            if (prop.options && !Array.isArray(prop.options)) {
                throw new Error(`组件 ${component.name} 的属性 ${prop.name} 的 options 必须是数组`);
            }
        }
    }

    // 加载所有配置的组件库
    async loadAllConfiguredLibraries(): Promise<void> {
        const config = vscode.workspace.getConfiguration('componentCompletion');
        const libraries = config.get<string[]>('enabledLibraries') || [];

        console.log(`开始加载配置的组件库: ${libraries.join(', ')}`);

        for (const library of libraries) {
            if (!this.dataStore.isLibraryLoaded(library)) {
                const success = await this.loadLibraryFromJson(library);
                if (!success) {
                    console.log(`跳过加载库: ${library}`, 'warn');
                }
            }
        }
    }

    // 重新加载所有组件库
    async reloadAllLibraries(): Promise<void> {
        this.dataStore.clear();
        await this.loadAllConfiguredLibraries();
    }

    // 设置文件变化监听
   setupFileWatcher(): vscode.FileSystemWatcher {
        const watcher = vscode.workspace.createFileSystemWatcher('**/*.json');
        
        watcher.onDidChange(async (uri) => {
            if (this.isComponentConfigFile(uri.fsPath)) {
                const libraryName = this.extractLibraryNameFromPath(uri.fsPath);
                if (libraryName && this.dataStore.isLibraryLoaded(libraryName)) {
                    console.log(`检测到 ${libraryName} 配置文件变化，重新加载...`);
                    await this.loadLibraryFromJson(libraryName);
                    vscode.window.showInformationMessage(`${libraryName} 组件配置已更新`);
                }
            }
        });

        watcher.onDidCreate(async (uri) => {
            if (this.isComponentConfigFile(uri.fsPath)) {
                const libraryName = this.extractLibraryNameFromPath(uri.fsPath);
                if (libraryName && !this.dataStore.isLibraryLoaded(libraryName)) {
                    console.log(`检测到新的组件配置文件: ${libraryName}`);
                    await this.loadLibraryFromJson(libraryName);
                }
            }
        });

        return watcher;
    }

    // 检查是否为组件配置文件
    private isComponentConfigFile(filePath: string): boolean {
        const fileName = path.basename(filePath);
        return fileName.endsWith('.json') && 
               (fileName.includes('-components') || 
                fileName.includes('components-') ||
                !fileName.includes('package'));
    }

    // 从文件路径提取库名称
    private extractLibraryNameFromPath(filePath: string): string | null {
        const fileName = path.basename(filePath, '.json');
        return fileName
            .replace('-components', '')
            .replace('components-', '');
    }

     /**
     * 获取已加载的库列表
     */
    getLoadedLibraries(): string[] {
        return this.dataStore.getLoadedLibraries();
    }

    /**
     * 获取所有组件数量
     */
    getTotalComponentsCount(): number {
        return this.dataStore.getAllComponents().length;
    }

    /**
     * 检查库是否已加载
     */
    isLibraryLoaded(libraryName: string): boolean {
        return this.dataStore.isLibraryLoaded(libraryName);
    }
}